namespace AltNetUK.Models.Inputs
{
    using System;
    using System.Globalization;
    using System.Text;

    public sealed class TextInput : Input
    {
        private IValidateText _validator;

        public TextInput(IValidateText validator)
        {
            this.Validator = validator;
        }

        public int? MaxLength
        {
            get;
            set;
        }

        public override string Type
        {
            get
            {
                return "text";
            }
        }

        public IValidateText Validator
        {
            get
            {
                return this._validator;
            }

            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                this._validator = value;
            }
        }

        public string Render(int tabIndex, string value)
        {
            return this.Render(tabIndex, value, default(int?));
        }

        public string Render(int tabIndex, string value, int? size)
        {
            if (1 > tabIndex)
            {
                throw new ArgumentOutOfRangeException("tabIndex");
            }
            else if (size.HasValue && (1 > size.Value))
            {
                throw new ArgumentOutOfRangeException("size");
            }

            StringBuilder buffer = new StringBuilder();

            buffer.Append(new Label(this, value));
            buffer.AppendFormat(
                CultureInfo.InvariantCulture,
                "<input id='{0}' name='{1}'{2}{3} tabindex='{4}' title='{5}'{6} />",
                this.Id,
                this.Name,
                this.MaxLength.HasValue ? string.Format(CultureInfo.InvariantCulture, " maxlength='{0}'", this.MaxLength.Value) : string.Empty,
                size.HasValue ? string.Format(CultureInfo.InvariantCulture, " size='{0}'", size.Value) : string.Empty,
                tabIndex,
                this.Title,
                (null == value) ? string.Empty : string.Format(CultureInfo.InvariantCulture, " value='{0}'", value)
                );

            return buffer.ToString();
        }

        public override ValidationResult Validate(string value)
        {
            return this.Validator.Validate(value);
        }
    }
}